package com.songshuai.webapi.logs.service.cust;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songshuai.webapi.logs.entity.CustomPermissionLogger;
import com.songshuai.webapi.logs.mqchannel.InputSource;
import com.songshuai.webapi.logs.repository.CustPermissionLogsRepository;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.integration.annotation.ServiceActivator;

import java.util.concurrent.CompletableFuture;

/**
 * Created by yubo on 2018/12/11.
 */
@EnableBinding(InputSource.class)
public class CustPermissionLogsService {
    private static Logger logger = LoggerFactory.getLogger(CustPermissionLogsService.class);

    @Autowired
    private CustPermissionLogsRepository custPermissionLogsRepository;


    @ServiceActivator(inputChannel = InputSource.CUSTPERMISSONCHANNEL,outputChannel = InputSource.REPLYCHANNEL)
    public CompletableFuture<String> accept(String loggingEvent) {
        return CompletableFuture.supplyAsync(() -> {
            System.out.println(loggingEvent);
            try {
                if(StringUtils.isNotBlank(loggingEvent)){
                    JSONObject jsonObject = JSON.parseObject(loggingEvent.replace("@",""));

                    CustomPermissionLogger cust=new CustomPermissionLogger();
                    cust.setClazz(jsonObject.getString("loggerName"));
                    String args = jsonObject.getString("argumentArray");
                    if(StringUtils.isNotBlank(args)){
                        cust.setArgs(args);
                    }
                    String throwable = jsonObject.getString("throwable");
                    if(StringUtils.isNotBlank(throwable)){
                        cust.setThrowable(throwable);
                    }
                    cust.setLevel(jsonObject.getString("level"));
                    cust.setMsg(jsonObject.getString("message"));
                    cust.setUsername(jsonObject.getString("threadName"));
                    custPermissionLogsRepository.save(cust);
                }
            } catch (Exception e) {
                    logger.info("保存自定义日志失败，CustPermissionLogsService："+e);
                }




            return "1";
        });
    }
}
